package com.wootion.dizhi.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.wootion.dizhi.dao.ConfigTypeDao;
import com.wootion.dizhi.dao.ConfigurationDao;
import com.wootion.dizhi.dao.CylinderDao;
import com.wootion.dizhi.dao.ResourcesDao;
import com.wootion.dizhi.exception.BusinessException;
import com.wootion.dizhi.response.Result;
import com.wootion.dizhi.service.SystemDataService;
import com.wootion.dizhi.utils.SqlExporter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Service
public class SystemDataServiceImpl implements SystemDataService {
    @Resource
    private DruidDataSource druidDataSource;
    @Resource
    private ResourcesDao resourcesDao;
    @Resource
    private ConfigTypeDao configTypeDao;
    @Resource
    private ConfigurationDao configurationDao;
    @Resource
    private CylinderDao cylinderDao;
    /**
     * 系统导入数据
     * @return
     */
    @Override
    public Result dataImport(MultipartFile multipartFile) throws IOException, BusinessException {
        //导入并覆盖“液位计-历史样品“、”气象色谱仪“数据、”类型设置“数据
        //获得原文件名
        String fileName = multipartFile.getOriginalFilename();
        //判断文件是否是excel文件
        assert fileName != null;
        if(!fileName.endsWith("sql")){
            throw new BusinessException("导入的文件格式不正确");
        }
        Set<String> strings = null;
        try {
            strings = this.uploadRtnMap(multipartFile);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("数据导入失败，请检查文件是否正确");
        }
        System.out.println(strings);
        //先清除原本这个四张表的数据 "config_type","configuration","resources","cylinder"
        configurationDao.delete(null);
        configTypeDao.delete(null);
        resourcesDao.delete(null);
        cylinderDao.delete(null);
        //然后执行文件中sql数据
        try {
            //获取一个链接
            Connection connection = druidDataSource.getConnection().getConnection();
            Statement statement = connection.createStatement();
            strings.forEach(sql->{
                try {
                    int i = statement.executeUpdate(sql);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            });
            statement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.success();
    }

    public Set<String> uploadRtnMap(MultipartFile file) throws IOException {
        InputStream is = null;
        InputStreamReader isReader = null;
        BufferedReader br = null;
        Set<String> phoneList = new HashSet<>();
        try {
            is = file.getInputStream();
            isReader = new InputStreamReader(is, StandardCharsets.UTF_8);
            br = new BufferedReader(isReader);
            //循环逐行读取
            String str;
            while ((str = br.readLine()) != null) {
                System.out.println(str);
                phoneList.add(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
            if (isReader != null) {
                isReader.close();
            }
            if (br != null) {
                br.close();
            }
        }
        return phoneList;
    }


    /**
     * 系统导出数据
     * @return
     */
    @Override
    public Result dataExport() {
        String outPath = "./out/";
        File exportDirFile = new File(outPath);
        if (!exportDirFile.exists()) {
            boolean mkdirs = exportDirFile.mkdirs();
            if(mkdirs){
                log.info("创建文件夹{}成功",exportDirFile);
            }else {
                log.error("创建文件夹失败");
            }
        }

        String outputPath = exportDirFile.getPath() + File.separator + "dizhi.sql";
        //1:先去删除
        File file = new File(outputPath);
        if (file.delete()) {
            System.out.println("文件删除成功");
        } else {
            System.out.println("文件删除失败");
        }
        //1.“液位计-历史样品“数据、2.”气象色谱仪“数据、3.”类型设置“数据
        try {
            SqlExporter sqlExporter = new SqlExporter(druidDataSource);
            String[] tableNames = new String[]{"config_type","configuration","resources","cylinder"};
            sqlExporter.export(tableNames,outputPath);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //将所有的windows \ 换成 / 以免Linux不支持
        return Result.success(outputPath.replace("\\", "/"));
    }
}
